<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <jsp:include page="../inc/js.jsp"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>公司管理</title>
    <jsp:include page="../inc/css.jsp"/>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <jsp:include page="../inc/menu.jsp"/>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Main content -->
        <!-- Main content -->
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card" style="margin-top: 10px">
                        <!-- /.card-header -->
                        <div class="card-header">
                            <button type="button" title="新增公司" class="btn btn-success" onclick="_companyList.fn.addInfo()">新增公司</button>

                            <c:if test="${sessionScope.is_localhost}">
                                <button type="button" title="同步原始数据" class="btn btn-info" onclick="_companyList.fn.syncData()"> 同步原始数据</button>
                                <button type="button" title="同步公司用户关联数据" class="btn btn-primary" onclick="_companyList.fn.syncCompanyUserData()"> 同步公司用户关联数据</button>
                                <button type="button" title="合并公司信息" class="btn btn-success" onclick="_companyList.fn.showMergeModal()"> 合并公司信息</button>
                            </c:if>

                            <div class="form-inline" style="margin-top: 10px;">
                                <div class="form-group">
                                    <input id="searchKeyWord" placeholder="公司名称" class="form-control"/>
                                </div>
                                <button type="button" title="查询" class="btn btn-info" style="margin-left: 10px;" onclick="_companyList.fn.reloadData()"> 查询</button>
                                <button type="button" title="重置搜索条件并查询" class="btn btn-success" style="margin-left: 10px;" onclick="_companyList.fn.resetAndReloadData()"> 重置</button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered table-hover" id="dataTables" style="width: 99%">
                                    <colgroup>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                    </colgroup>
                                    <thead>
                                    <tr>
                                        <th>公司名称</th>
                                        <th>联系人</th>
                                        <th style="width: 60px">设备数</th>
                                        <th style="width: 60px">用户数</th>
                                        <th style="max-width: 160px">录入时间</th>
                                        <th style="max-width: 160px">过期时间</th>
                                        <th style="width: 120px">操作</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <!-- /.card-body -->
                    </div>
                    <!-- /.card -->
                </div>
                <!-- /.col -->
            </div>
            <!-- /.row -->
        </section>
        <!-- /.content -->
    </div>
</div>
<!-- ./wrapper -->

<div class="modal inModal fade" id="companyModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">公司详情</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <form role="form" class="form-group">
                    <input type="hidden" id="companyId"/>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-3">公司名称：</label>

                        <div class="col-9">
                            <input type="text" id="companyName" maxlength="30" class="form-control" style="width: 95%"/>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-3">过期时间：</label>

                        <div class="col-9">
                            <input id="companyEndTime" readonly placeholder="过期时间" class="form-control" style="width: 150px"/>
                        </div>
                    </div>
                </form>

                <div class="form-inline" style="display: none;text-align: center;">
                    <img id="companyCodeUrl" width="300px" height="300px"/>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="_companyList.fn.saveInfo()">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<div class="modal inModal fade" id="mergeModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">合并公司信息</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <form role="form" class="form-group">
                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-3">主公司：</label>

                        <div class="col-9">
                            <select id="mainCompanyList" class="form-control" style="width: 100%"></select>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-3">次公司：</label>

                        <div class="col-9">
                            <select id="otherCompanyList" class="form-control" style="width: 100%"></select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="_companyList.fn.mergeInfo()">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- page script -->
<script type="text/javascript">
    let _companyList = {
        v: {
            list: [],
            dTable: null
        },
        fn: {
            init: function () {
                laydate.render({
                    elem: '#companyEndTime'
                    , type: 'date'
                });

                _companyList.fn.getCompanyList();

                _companyList.fn.dataTableInit();
            },
            reloadData: function () {
                _companyList.v.list = [];
                _companyList.v.dTable.DataTable().ajax.reload(null, false);

                _companyList.fn.getCompanyList();
            },
            resetAndReloadData: function () {
                $('#searchKeyWord').val('');

                _companyList.fn.reloadData();
            },
            getCompanyList: function () {
                $.post('common/companyList', {
                    id: Math.random()
                }, function (result) {
                    if (result.length > 0) {
                        let content = '<option value="">请选择公司</option>';

                        $.each(result, function (i, item) {
                            content += '<option value="' + item.id + '">' + item.name + '</option>';
                        });

                        $('#mainCompanyList').html(content);
                        $('#otherCompanyList').html(content);
                    } else {
                        info("暂无公司数据", "error");
                    }
                });
            },
            dataTableInit: function () {
                _companyList.v.dTable = $tutu.dataTable($('#dataTables'), {
                    "processing": true,
                    "serverSide": true,
                    "autoWidth": true,//自动计算宽度
                    "lengthChange": false,//是否允许用户改变表格每页显示的记录数
                    "searching": false,
                    "ordering": false,
                    "ajax": {
                        "url": "backend/company/list",
                        "type": "POST"
                    },
                    "language": $tutu.v.dataTableL,
                    "columns": [
                        {"data": "name"},
                        {
                            "data": "contactList",
                            render: function (data) {
                                if (data.length > 0) {
                                    let contactName = '';

                                    $.each(data, function (i, item) {
                                        contactName += item.name + "、";
                                    });

                                    if (contactName.length > 0) contactName = contactName.substring(0, contactName.length - 1);

                                    return formatStr(contactName, 10);
                                } else {
                                    return "";
                                }
                            }
                        },
                        {"data": "currentDeviceCount"},
                        {"data": "userCount"},
                        {
                            "data": "createTime",
                            render: function (data) {
                                return crtTimeFtt(data);
                            }
                        },
                        {
                            "data": "endTime",
                            render: function (data) {
                                return crtTimeFtt(data);
                            }
                        },
                        {"data": null}
                    ],
                    /*添加小插件*/
                    "columnDefs": [
                        {
                            "data": null,
                            "defaultContent": "<button type='button' title='用户列表' class='btn btn-info btn-sm childList'><i class='fa fa-list'></i></button>" +
                                "&nbsp;&nbsp;" +
                                "<button type='button' title='编辑' class='btn btn-primary btn-sm edit'><i class='fa fa-edit'></i></button>" +
                                "&nbsp;&nbsp;" +
                                "<button type='button' title='删除' class='btn btn-danger btn-sm delete'><i class='fa fa-remove'></i></button>",
                            "targets": -1
                        }
                    ],
                    /*展示数据格式化*/
                    "createdRow": function (row, data, index) {
                        _companyList.v.list.push(data);
                    },
                    stateSave: true, // 启用状态保存
                    stateSaveCallback: function (settings, data) {
                        localStorage.setItem('DataTables_' + settings.sInstance, JSON.stringify(data));
                    },
                    stateLoadCallback: function (settings) {
                        return JSON.parse(localStorage.getItem('DataTables_' + settings.sInstance));
                    },
                    /*回调函数*/
                    rowCallback: function (row, data) {
                        $('td', row).last().find(".childList").click(function () {
                            if (Number(data.currentDeviceCount) > 0) {
                                window.location.href = 'backend/company/child/index?id=' + data.id + '&pageNum=' + $tutu.currentPage;
                            } else {
                                info('请先添加设备信息', "error");
                            }
                        });

                        $('td', row).last().find(".edit").click(function () {
                            _companyList.fn.editInfo(data);
                        });

                        $('td', row).last().find(".delete").click(function () {
                            _companyList.fn.delInfo(data.id);
                        });
                    },
                    /*带参数*/
                    "fnServerParams": function (aoData) {
                        _companyList.v.list = [];
                        aoData.keyWord = $('#searchKeyWord').val();
                    },
                    "fnDrawCallback": function (data) {
                        $tutu.uiForm(data);
                    }
                });
            },
            syncData: function () {
                $.post('backend/company/sync', {
                    id: 1
                }, function (result) {
                    if (result.code === 0) {
                        info("信息已同步", "success");

                        _companyList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            syncCompanyUserData: function () {
                $.post('backend/device/syncDeviceUser', {
                    id: 1
                }, function (result) {
                    if (result.code === 0) {
                        info("信息已同步", "success");

                        _companyList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            showMergeModal: function () {
                $("#mergeModal").modal("show");
            },
            mergeInfo: function () {
                let mainCompanyId = $('#mainCompanyList').val();
                let otherCompanyId = $('#otherCompanyList').val();

                if (mainCompanyId === '') {
                    info('请选择主公司', "error");
                    return;
                }

                if (otherCompanyId === '') {
                    info('请选择子公司', "error");
                    return;
                }

                startLoading();

                $.post('backend/company/mergeInfo', {
                    mainCompanyId: mainCompanyId,
                    otherCompanyId: otherCompanyId
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("公司信息已合并", "success");

                        $("#mergeModal").modal("hide");

                        _companyList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            saveInfo: function () {
                let name = $('#companyName').val();

                if (name === '') {
                    info('请输入公司名称', "error");
                    return;
                }

                startLoading();

                $.post('backend/company/save', {
                    id: $('#companyId').val(),
                    name: name,
                    endTime: $('#companyEndTime').val()
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("信息已保存", "success");

                        $("#companyModal").modal("hide");

                        _companyList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            editInfo: function (data) {
                $('#companyId').val(data.id);
                $('#companyName').val(data.name);
                $('#companyEndTime').val(formatDate(data.endTime));
                $('#companyCodeUrl').parent().css('display', 'block');
                $('#companyCodeUrl').prop('src', 'wx/showQrCodeImg?companyId=' + data.id);

                $("#companyModal").modal("show");
            },
            addInfo: function () {
                $('#companyId').val('');
                $('#companyName').val('');
                $('#companyEndTime').val('');
                $('#companyCodeUrl').parent().css('display', 'none');
                $('#companyCodeUrl').prop('src', '');

                $("#companyModal").modal("show");
            },
            delInfo: function (id) {
                swal({
                    title: "您确定要删除这条记录吗",
                    text: "删除后将无法恢复，请谨慎操作！",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "是的，删除！",
                    cancelButtonText: "不，取消",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function (isConfirm) {
                    if (isConfirm) {
                        startLoading();

                        $.post('backend/company/del', {
                            id: id
                        }, function (result) {
                            endLoading();

                            if (result.code === 0) {
                                swal("删除成功！", "您已经删除了这条记录。", "success");

                                _companyList.fn.reloadData();
                            } else {
                                info(result.msg, "error");
                            }
                        });
                    } else {
                        swal("已取消", "您取消了删除操作！", "error");
                    }
                })
            }
        }
    };

    $(document).ready(function () {
        _companyList.fn.init();

        window.onload = function () {
            checkSelectMenu("companyLi");

            loadMenuColor('companyLi');
        }
    });
</script>
</body>
</html>